import Taro from '@tarojs/taro';
import config from './config'
import user from '@/store/user';
import {ShowToast, tarBarPages} from '@/utils';

let timer
const toLogin = () => {
  console.log('去登录页')
  if (timer) {
    clearTimeout(timer)
  }
  const pages = Taro.getCurrentPages()
  const page = pages[pages.length - 1]
  // // 避免反复编码
  const fullPath = decodeURIComponent(page.$taroPath)
  timer = setTimeout(() => {
    // tab页面不重定向
    if (!tarBarPages.includes(page.route || '')){
      if (page.route === 'pages/mine/index') {
        Taro.redirectTo({
          url: '/pages/login/index'
        })
      } else {
        Taro.redirectTo({
          url: `/pages/login/index?redirect=${encodeURIComponent(`/${fullPath}`)}`
        })
      }
    } else {
      ShowToast('身份信息无效，请重新登录')
    }
  }, 500)
}
type MethodKeys = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'CONNECT';
const Request = (url, params, method: MethodKeys = 'GET') => {
  const userInfo = user.info
  const token = userInfo?.token || ''
  return Taro.request({
    url: url.indexOf('http') === 0 ? url : config.BASE_URL + url, // 请求的 URL
    method: method, // HTTP 请求方法
    data: params,
    header: {
      'content-type': 'application/json',
      Authorization: token,
      AppNice: 'tr-api',
      AppPassWd: 'tr-api',
      client_id: 'webApp',
      client_secret: 'webApp',
    }
  }).then(res => {
    console.log({
      url,
      params,
      method,
      res
    })
    if (res.data.code === 200) {
      return res.data
    } else if (res.data.code === 401) {
      // 没权限时清空已有身份信息
      user.updateInfo({})
      toLogin()
    } else if (url.indexOf('http') === 0) {
      // 部分第三方接口不拦截
      return res
    }
    throw res.data || res
  }).catch(err => {
    if (err.statusCode === 401) {
      toLogin()
    }
    throw err
  });
}
Request.post = (url, params = {}) => Request(url, params, 'POST')
Request.get = (url, params = {}) => Request(url, params, 'GET')
Request.put = (url, params = {}) => Request(url, params, 'PUT')
Request.delete = (url, params = {}) => Request(url, params, 'DELETE')

const http = Request
export default http
